<?php

namespace addons\shopro\controller;

use addons\shopro\model\User;
use baofu\BaofuBank;
use baofu\Util\Log;
use think\Db;
use think\Exception;

use addons\shopro\model\Cats;
use app\admin\model\AdminLog;
use app\admin\model\CatOrder;
use app\common\model\UserBaofuBank;

use think\Loader;
use think\Request;

//分账支付
//https://docs.baofu.com/docs/interface_document/protocolSplitPay-rsa

//问题汇总
//https://docs.baofu.com/docs/interface_document/protocolPay-QA

/**
 * 首页接口
 */
class BaofuPay extends Base
{
    protected $noNeedLogin = ['unsign', 'bank_code', 'baofu_agreement'];
    protected $noNeedRight = ['*'];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);


        $config = Db::name('config')->where('group', 'baofu')->column('value', 'name');

        Loader::import("\baofu\baofu", EXTEND_PATH);
        $this->baofu = new \baofu\Baofu($config);
    }

    public function bank_code()
    {
        //$list = Db::name('baofu_agreement')->where('type', 2)->field('code,name')->select();
        $list = [
            ['code' => 'ICBC', 'name' => '中国工商银行'],
            ['code' => 'ABC', 'name' => '中国农业银行'],
            ['code' => 'CCB', 'name' => '中国建设银行'],
            ['code' => 'BOC', 'name' => '中国银行'],
            ['code' => 'BCOM', 'name' => '中国交通银行'],
            ['code' => 'CIB', 'name' => '兴业银行'],
            ['code' => 'CITIC', 'name' => '中信银行'],
            ['code' => 'CEB', 'name' => '中国光大银行'],
            ['code' => 'PAB', 'name' => '平安银行'],
            ['code' => 'PSBC', 'name' => '中国邮政储蓄银行'],
            ['code' => 'SHB', 'name' => '上海银行'],
            ['code' => 'SPDB', 'name' => '浦东发展银行'],
            ['code' => 'CMBC', 'name' => '中国民生银行'],
            ['code' => 'CMB', 'name' => '招商银行'],
            ['code' => 'GDB', 'name' => '广发银行']
        ];

        $this->success('银行编码', $list);
    }

    public function baofu_agreement()
    {
        $id = $this->request->param('id');
        $code = $this->request->param('code');
        if (empty($id) && empty($code)) {
            $this->error('参数有误');
        }
        if (!empty($id)) {
            $info = Db::name('baofu_agreement')->where('id', $id)->field('title,content')->find();
            $this->success('成功', ['info' => $info, 'list' => []]);
        }
        if (!empty($code)) {
            //获取用户需要同意的协议
            $list = Db::name('baofu_agreement')->where('code', $code)->whereOr('type', 1)->field('id,title')->select();
            $this->success('成功', ['info' => [], 'list' => $list]);
        }
    }


    //预绑卡接口
    public function readySign()
    {
        $user = User::info();
        $user_id = $user->id;
        $card_type = $this->request->param('card_type', '101');  //卡类型  101	借记卡，102 信用卡
        $bank_card_code = $this->request->param('card_code'); //银行卡号
        $cardholder_name = $this->request->param('cardholder_name', ''); //持卡人名称
        $id_number = $this->request->param('id_number', ''); //证件号， 身份证号
        $phone = $this->request->param('phone'); //手机号码
        $bank_card_security_code = $this->request->param('bank_card_security_code', ''); //银行卡安全码
        $bank_card_validity_period = $this->request->param('bank_card_validity_period', ''); //银行卡有效期

        //获得待签约订单
        $order_sn = $this->request->param('order_sn');  //订单编号
        $orderInfo = CatOrder::where('user_id', $user_id)
            ->where('status', 0)//订单状态:-2=交易关闭,-1=已取消,0=待签约,1=已签约,2=已完成,3已经解约
            ->where('order_sn', $order_sn)//订单编号
            ->find();

        if ($orderInfo == null) {
            $this->error('待签订单未找到');
        }

        if (empty($bank_card_code) || empty($cardholder_name) || empty($id_number) || empty($phone)) {
            $this->error('参数有误');
        }

        if (!validatePhoneNumber($phone)) {
            $this->error('手机号码验证失败');
        }

        if (!validateIdCardNumber($id_number)) {
            $this->error('证件验证失败');
        }

        //判断当前银行卡是否已经被绑定了
        $info = Db::name('user_baofu_bank')->where('card_code', $bank_card_code)->where('status', '2')->find();

        if ($info) {
            $this->error('当前银行卡还在周期付款中,请签约新的银行卡');
        }

        //清空当前订单的预绑卡信息
        (new UserBaofuBank())->where('order_id', $orderInfo['id'])->delete();

        //账户信息  [银行卡号|持卡人姓名|证件号|手机号|银行卡安全码|银行卡有效期]
        $Cardinfo = "{$bank_card_code}|{$cardholder_name}|{$id_number}|{$phone}|{$bank_card_security_code}|{$bank_card_validity_period}";

        try {

            $baofuData = [
                "user_id" => $user_id,
                'msg_id' => $this->baofu->getMsgID()
            ];

            $result = $this->baofu->readySign($Cardinfo, $baofuData);

            if (isset($result['code']) && $result['code'] == 200) {
                $data = [
                    'user_id' => $user_id,
                    'card_type' => $card_type,
                    'bank_name' => '预绑卡',
                    'card_code' => $bank_card_code,
                    'cardholder_name' => $cardholder_name,
                    'id_number' => $id_number,
                    'phone' => $phone,
                    'bank_card_security_code' => $bank_card_security_code,
                    'bank_card_validity_period' => $bank_card_validity_period,
                    'unique_code' => $result['data']['unique_code'],
                    'createtime' => time(),
                    'updatetime' => time(),
                    'status' => '1',
                    'order_id' => $orderInfo['id'],
                ];

                $id = (new UserBaofuBank())->insertGetId($data);

                if ($id !== false) {
                    $insert = [
                        'title' => '发起签约',
                        'content' => '发起签约,签约订单编号' . $order_sn,
                        'url' => substr(request()->url(), 0, 1500),
                        'admin_id' => 1,
                        'username' => $user_id . '-发起签约',
                        'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
                        'ip' => request()->ip()
                    ];
                    AdminLog::insert($insert);

                    $this->success('发起签约', ['id' => $id]);
                } else {
                    $this->error('签约失败');
                }
            } else {
                $this->error('签约失败');
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    //确认绑卡
    public function confirmSign()
    {
        $user = User::info();
        $user_id = $user->id;
        $sms_code = $this->request->param('sms_code');  //短信验证码
        $id = $this->request->param('id');

        $model = new UserBaofuBank();

        $info = $model->where(['id' => $id, 'status' => 1])->find();

        if (!$info) {
            $this->error('预绑卡信息未找到');
        }

        $orderInfo = CatOrder::where('id', $info['order_id'])->find();
        $time = time();
        try {
            $UniqueCode = "{$info['unique_code']}|{$sms_code}";
            $result = $this->baofu->confirmSign($UniqueCode);
            if (isset($result['code'])) {
                if ($result['code'] == 200) {
                    $data = [
                        'protocol_no' => $result['data']['protocol_no'],
                        'status' => 2,
                        'updatetime' => $time,
                        'confirmtime' => $time
                    ];

                    $model->where('id', $info['id'])->update($data);

                    $insert = [
                        'title' => '签约成功',
                        'content' => '签约成功,签约订单编号' . $orderInfo['order_sn'],
                        'url' => substr(request()->url(), 0, 1500),
                        'admin_id' => 1,
                        'username' => '签约成功',
                        'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
                        'ip' => request()->ip()
                    ];
                    AdminLog::insert($insert);

                    $RiskItem = [];
                    $RiskItem["goodsCategory"] = "01";//商品类目 详见附录《商品类目》
                    $RiskItem["chPayIp"] = "127.0.0.1";//持卡人支付IP

                    /**--------电商行业参数-------------**/
                    $RiskItem["csName"] = $orderInfo['consignee'];    //收货人姓名
                    $RiskItem["csMobile"] = $orderInfo['phone'];  //收货人手机
                    $RiskItem["csProvince"] = $orderInfo['csProvince'];          //收货人省份
                    $RiskItem["csCity"] = $orderInfo['csCity'];             //收货人城市
                    $RiskItem["csAddress"] = $orderInfo['address'];            //收货人地址
                    $RiskItem["prodNameList"] = $orderInfo['breed_name'];       //商品名称
                    $RiskItem["prodTypeList"] = "20";       //商品类目
                    $RiskItem["prodQtyList"] = "1";        //商品数量
                    $RiskItem["prodAmtList"] = $orderInfo['total_amount'];        //商品总价
                    $RiskItem = json_encode($RiskItem);//加入风控参数(固定为JSON字串)

                    //获得待签约订单
                    CatOrder::where('id', $info['order_id'])
                        ->where('status', 0)//订单状态:-2=交易关闭,-1=已取消,0=待签约,1=已签约,2=已完成
                        ->update([
                            'status' => 1,
                            'agreement_no' => $result['data']['protocol_no'],
                            'protocol_no' => $result['data']['protocol_no'],
                            'cycletime' => $time,
                            'RiskItem' => $RiskItem,
                        ]);

                    Cats::where('id', $orderInfo['cat_id'])->update(['type' => 0]);//猫咪改为已签约

                    //用户支付 TODO 分期付款
//                    $pay_time = strtotime($orderInfo['deduction_time']);
                    $pay_time = getNextMonthDays($orderInfo);
                    Log::LogWirte('支付时间:' . date('Y-m-d H:i:s', $pay_time));
                    \think\Queue::later(($pay_time - $time), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');

                    $this->success('签约成功', '', 1);
                } elseif ($result['code'] == 201) {

                    $insert = [
                        'title' => '签约处理中',
                        'content' => '签约处理中,订单编号' . $orderInfo['order_sn'],
                        'url' => substr(request()->url(), 0, 1500),
                        'admin_id' => 1,
                        'username' => '签约处理',
                        'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
                        'ip' => request()->ip()
                    ];
                    AdminLog::insert($insert);

                    //处理中
                    $model->where('id', $info['id'])->update(['status' => 4, 'updatetime' => $time]);

                    CatOrder::where('id', $info['order_id'])->where('status', 0)->update(['status' => 6]);

                    //绑定结果查询
                    \think\Queue::later(10, '\addons\shopro\job\OrderAutoOper@baofuQueryBind', ['baofu' => $info], 'shopro');

                    $this->success('签约中,5分钟内给你回复', '', 201);
                }
            }

            $insert = [
                'title' => '签约失败',
                'content' => '签约失败,订单编号' . $orderInfo['order_sn'],
                'url' => substr(request()->url(), 0, 1500),
                'admin_id' => 1,
                'username' => '签约处理',
                'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
                'ip' => request()->ip()
            ];
            AdminLog::insert($insert);

            $this->error('确认绑卡失败');
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }

    }


    //商户解约
    public function unsign($order_sn)
    {
        $orderInfo = CatOrder::where('order_sn', $order_sn)->where('status', 1)->find();
        if ($orderInfo == null) {
            $this->error('签约信息未找到');
        }
        $insert = [
            'title' => '商户解约解约',
            'content' => '商户解约',
            'url' => substr(request()->url(), 0, 1500),
            'admin_id' => 1,
            'username' => '用户解约',
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip' => request()->ip()
        ];
        AdminLog::insert($insert);
        //解约
        CatOrder::where('order_sn', $order_sn)->update(['status' => 3, 'unsign' => 2, 'updatetime' => time()]);//1用户解约，2商户解约

        //银行卡解约
        $this->baofu->ABolishBind($orderInfo['protocol_no'], $orderInfo['user_id']);

        //修改绑卡状态
        (new UserBaofuBank())->where('protocol_no', $orderInfo['protocol_no'])->update(['updatetime' => time(), 'status' => 3, 'unbindtime' => time()]);

        $this->success('解约成功');
    }


    //退款接口
    public function refund($order)
    {
        $aop = new \AopClientSelf();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $object = new \stdClass();
        $object->out_trade_no = $order['order_sn'];//商户订单号
        $object->refund_amount = $order['month_money'];//退款金额。 需要退款的金额
        $object->out_request_no = 'refund' . time();//退款请求号。 标识一次退款请求，需要保证在交易号下唯一，如需部分退款，则此参数必传
        $json = json_encode($object);
        $request = new \AlipayTradeRefundRequest();
        $request->setBizContent($json);
        $result = $aop->execute($request);
        if ($result->alipay_trade_refund_response->code === 10000) {
            //退款成功
            CatOrder::where('order_sn', $order['order_sn'])
                ->update(['status' => 5, 'trade_no' => $result->alipay_trade_refund_response->trade_no, 'refundtime' => time()]);
            return $result->alipay_trade_refund_response->code;
        } else {
            return $result->alipay_trade_refund_response->msg;
        }
    }


}
